<template>
  <el-dialog
    :model-value="visible"
    :title="isEdit ? '编辑导入配置' : '新建导入配置'"
    width="600px"
    @update:model-value="handleClose"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="配置名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入配置名称"
          clearable
        />
      </el-form-item>

      <el-form-item label="文件类型" prop="fileType">
        <el-select
          v-model="formData.fileType"
          placeholder="请选择文件类型"
          style="width: 100%"
        >
          <el-option label="比分文件" value="score" />
          <el-option label="首页文件" value="homepage" />
        </el-select>
      </el-form-item>

      <el-form-item label="导入路径" prop="importPath">
        <el-input
          v-model="formData.importPath"
          placeholder="请输入服务器文件路径"
          clearable
        />
      </el-form-item>

      <el-form-item label="执行频率" prop="frequency">
        <el-select
          v-model="formData.frequency"
          placeholder="请选择执行频率"
          style="width: 100%"
        >
          <el-option label="每日执行" value="daily" />
          <el-option label="每小时执行" value="hourly" />
          <el-option label="手动执行" value="manual" />
        </el-select>
      </el-form-item>

      <el-form-item label="执行时间" prop="executeTime">
        <div class="flex items-center space-x-2">
          <el-select
            v-model="formData.importHour"
            placeholder="小时"
            style="width: 80px"
          >
            <el-option
              v-for="hour in 24"
              :key="hour - 1"
              :label="(hour - 1).toString().padStart(2, '0')"
              :value="hour - 1"
            />
          </el-select>
          <span>:</span>
          <el-select
            v-model="formData.importMinute"
            placeholder="分钟"
            style="width: 80px"
          >
            <el-option
              v-for="minute in 60"
              :key="minute - 1"
              :label="(minute - 1).toString().padStart(2, '0')"
              :value="minute - 1"
            />
          </el-select>
        </div>
      </el-form-item>

      <el-form-item label="状态">
        <el-switch
          v-model="formData.isEnabled"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>

      <el-form-item label="间隔时间" prop="intervalMinutes" v-if="formData.frequency === 'hourly'">
        <div class="flex items-center space-x-2">
          <el-input-number
            v-model="formData.intervalMinutes"
            :min="1"
            :max="60"
            placeholder="间隔分钟数"
            style="width: 120px"
          />
          <span>分钟</span>
        </div>
      </el-form-item>

      <el-form-item label="最大重试" prop="maxRetries">
        <div class="flex items-center space-x-2">
          <el-input-number
            v-model="formData.maxRetries"
            :min="0"
            :max="10"
            placeholder="重试次数"
            style="width: 120px"
          />
          <span>次</span>
        </div>
      </el-form-item>

      <el-form-item label="重试间隔" prop="retryIntervalMinutes">
        <div class="flex items-center space-x-2">
          <el-input-number
            v-model="formData.retryIntervalMinutes"
            :min="1"
            :max="60"
            placeholder="重试间隔"
            style="width: 120px"
          />
          <span>分钟</span>
        </div>
      </el-form-item>

      <el-form-item label="描述">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入配置描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ isEdit ? "更新" : "创建" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, reactive } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import {
  createImportConfig,
  updateImportConfig,
  type ImportConfig,
  type CreateImportConfigParams,
  type FileType,
  type FrequencyType
} from "@/api/automation";

// 组件属性
interface Props {
  visible: boolean;
  config?: ImportConfig | null;
  isEdit: boolean;
}

// 组件事件
interface Emits {
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 表单引用
const formRef = ref<FormInstance>();
const submitting = ref(false);

// 表单数据
const formData = reactive<CreateImportConfigParams>({
  name: "",
  importPath: "",
  fileType: "homepage" as FileType,
  frequency: "daily" as FrequencyType,
  isEnabled: true,
  description: "",
  importHour: 12,
  importMinute: 35,
  intervalMinutes: 30,
  maxRetries: 3,
  retryIntervalMinutes: 5
});

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: "请输入配置名称", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "配置名称长度在 2 到 50 个字符",
      trigger: "blur"
    }
  ],
  fileType: [{ required: true, message: "请选择文件类型", trigger: "change" }],
  frequency: [{ required: true, message: "请选择执行频率", trigger: "change" }],
  importPath: [{ required: true, message: "请输入导入路径", trigger: "blur" }],
  intervalMinutes: [
    {
      validator: (rule, value, callback) => {
        if (formData.frequency === 'hourly' && (!value || value < 1 || value > 60)) {
          callback(new Error("间隔时间必须在 1-60 分钟之间"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  maxRetries: [
    {
      validator: (rule, value, callback) => {
        if (value < 0 || value > 10) {
          callback(new Error("最大重试次数必须在 0-10 之间"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  retryIntervalMinutes: [
    {
      validator: (rule, value, callback) => {
        if (!value || value < 1 || value > 60) {
          callback(new Error("重试间隔必须在 1-60 分钟之间"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  executeTime: [
    {
      validator: (rule, value, callback) => {
        if (formData.importHour < 0 || formData.importHour > 23) {
          callback(new Error("小时必须在 0-23 之间"));
        } else if (formData.importMinute < 0 || formData.importMinute > 59) {
          callback(new Error("分钟必须在 0-59 之间"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ]
};

// 重置表单数据
const resetFormData = () => {
  formData.name = "";
  formData.importPath = "";
  formData.fileType = "homepage" as FileType;
  formData.frequency = "daily" as FrequencyType;
  formData.isEnabled = true;
  formData.description = "";
  formData.importHour = 12;
  formData.importMinute = 35;
  formData.intervalMinutes = 30;
  formData.maxRetries = 3;
  formData.retryIntervalMinutes = 5;
};

// 监听配置变化，填充表单
watch(
  () => props.config,
  newConfig => {
    if (newConfig && props.isEdit) {
      formData.name = newConfig.name;
      formData.importPath = newConfig.importPath;
      formData.fileType = newConfig.fileType || "homepage";
      formData.frequency = newConfig.frequency || "daily";
      formData.isEnabled = newConfig.isEnabled;
      formData.description = newConfig.description || "";
      formData.importHour = newConfig.importHour;
      formData.importMinute = newConfig.importMinute;
      formData.intervalMinutes = newConfig.intervalMinutes || 30;
      formData.maxRetries = newConfig.maxRetries || 3;
      formData.retryIntervalMinutes = newConfig.retryIntervalMinutes || 5;
    } else {
      resetFormData();
    }
  },
  { immediate: true }
);

// 监听对话框显示状态
watch(
  () => props.visible,
  visible => {
    if (visible && !props.isEdit) {
      resetFormData();
    }
    if (!visible) {
      formRef.value?.clearValidate();
    }
  }
);

// 关闭对话框
const handleClose = () => {
  emit("update:visible", false);
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    const valid = await formRef.value.validate();
    if (!valid) return;

    submitting.value = true;

    const submitData: CreateImportConfigParams = {
      name: formData.name,
      importPath: formData.importPath,
      fileType: formData.fileType,
      frequency: formData.frequency,
      isEnabled: formData.isEnabled,
      description: formData.description,
      importHour: formData.importHour,
      importMinute: formData.importMinute,
      intervalMinutes: formData.intervalMinutes,
      maxRetries: formData.maxRetries,
      retryIntervalMinutes: formData.retryIntervalMinutes
    };

    let response;
    if (props.isEdit && props.config?.id) {
      response = await updateImportConfig(props.config.id, submitData);
    } else {
      response = await createImportConfig(submitData);
    }

    if (response.code === 0) {
      ElMessage.success(props.isEdit ? "更新成功" : "创建成功");
      emit("success");
    } else {
      ElMessage.error(response.message || (props.isEdit ? "更新失败" : "创建失败"));
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error(props.isEdit ? "更新失败" : "创建失败");
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.space-x-2 > * + * {
  margin-left: 8px;
}
</style>
